import tool from '../modules/tool'
const controls = tool.cControls
import { useStore } from '../modules/store'
const store = useStore()

export default async (refreshPage, handleError) => {

    const question = {
        selected: undefined,
        async selectFile() {
            let re = await tool.selectFiles(['doc', 'docx', 'pdf'], 1)
            if (re && re.length) {
                await tool.flow(async () => {
                    this.selected = re[0]
                    refreshPage()
                    let re_file = await tool.uploadFile('/file/upload', (() => {
                        let data = new FormData()
                        data.append('file', this.selected.file)
                        return data
                    })())
                    try {
                        re_file = JSON.parse(re_file)
                    } catch (error) {

                    }
                    let re_parse = await tool.requestData('/tool/parseQuestionDoc', {}, { fileName: re_file.data }, 'post')
                    if (re_parse.status) {
                        // await tool.object.for(re_parse.data.report, (k, v) => {
                        //     v.forEach(item => {
                        //         item = parseInt(item)
                        //         for (let i = 0; i < re_parse.data.parsed.length; i++) {
                        //             if (re_parse.data.parsed[i].index === item) {
                        //                 if (re_parse.data.parsed[i].needCheck === undefined) {
                        //                     re_parse.data.parsed[i].needCheck = []
                        //                 }
                        //                 re_parse.data.parsed[i].needCheck.push(k)
                        //                 break
                        //             }
                        //         }
                        //     })
                        // })
                        this.data = [...this.data, ...re_parse.data.parsed]
                        this.resetQuestionIndexes()
                        this.report = re_parse.data.report
                        this.waitingForUpload = 1
                    } else {
                        throw re_parse.content
                    }
                    refreshPage()
                }, err => {
                    tool.toast.error(`${err}`)
                })
            }
        },
        data: [],
        report: {},
        async showReport(noReportToast = true) {
            if (Object.keys(this.report).length === 0) {
                if (!noReportToast) {
                    store.showModal2('提示', '当前文件未发现异常题目。', () => { }, false)
                }
            } else {
                let str = ''
                await tool.object.for(this.report, (key, value) => {
                    str += `${key}：${value.join(', ')}\n`
                })
                store.showModal2('解析报告', str, () => { }, false)
            }
        },
        resetQuestionIndexes() {
            for (let i = 0; i < this.data.length; i++) {
                this.data[i].index = i + 1
            }
            refreshPage()
        },
        mselect: controls.mSelectObject(),
        waitingForUpload: 0,

    }

    const answer = {
        selected: undefined,
        async selectFile() {
            let re = await tool.selectFiles(['doc', 'docx', 'pdf'], 1)
            if (re && re.length) {
                await tool.flow(async () => {
                    this.selected = re[0]
                    refreshPage()
                    let re_upload = await tool.uploadFile('/file/upload', (() => {
                        let a = new FormData()
                        a.append('file', this.selected.file)
                        return a
                    })())
                    try {
                        re_upload = JSON.parse(re_upload)
                    } catch (error) {

                    }
                    if (!re_upload.status) throw re_upload.content
                    let re_parse = await tool.requestData('/tool/parseAnswerDoc', {}, {
                        fileName: re_upload.data
                    }, 'post')
                    if (re_parse.status) {

                    } else {
                        throw re_parse.content
                    }

                    for (let i = 0; i < question.data.length; i++) {
                        let currentIndex = question.data[i].index
                        if (re_parse.data[currentIndex] !== undefined) {
                            question.data[i] = {
                                ...question.data[i],
                                ...re_parse.data[currentIndex],
                            }
                        }
                    }

                    question.waitingForUpload = 2

                    refreshPage()
                }, err => {
                    tool.toast.error(`${err}`)
                })
            }
        }
    }

    const paperInfo = {
        categoryId: null,
        paperName: ''
    }

    let data = tool.event.getItem('question-import')
    tool.event.removeItem('question-import')
    if (data) {
        let item = data.item
        paperInfo.categoryId = item.categoryId
        paperInfo.paperName = item.paperName

        data = data.data
        for (let i = 0; i < data.parsed.length; i++) {
            data.parsed[i].options = {
                A: data.parsed[i].optionA,
                B: data.parsed[i].optionB,
                C: data.parsed[i].optionC,
                D: data.parsed[i].optionD,
            }
            data.parsed[i].optionTypes = {
                A: data.parsed[i].optionAType,
                B: data.parsed[i].optionBType,
                C: data.parsed[i].optionCType,
                D: data.parsed[i].optionDType,
            }
        }
        question.data = data.parsed
        question.waitingForUpload = 2
        question.resetQuestionIndexes()
    }

    const refresh = async () => {
        return {
            type: 1,
            main: {
                tab: [
                    {
                        title: '添加题目',
                        bottomControls: [],
                        topControls: [
                            ...(() => {
                                const add = () => {
                                    return controls.button({
                                        title: '手动添加',
                                        leftIcon: 'add',
                                        callBack() {
                                            tool.forms.question.add((e1, fm) => {
                                                if (Object.keys(e1).length === 0) {
                                                    store.hideModal2()
                                                    return
                                                }
                                                e1.options.A = e1.optionA
                                                e1.options.B = e1.optionB
                                                e1.options.C = e1.optionC
                                                e1.options.D = e1.optionD
                                                let check = tool.checkQuestionItem(e1)
                                                if (check.length) {
                                                    store.showModal2('无法保存编辑', check.join('、'), () => {
                                                        store.hideModal2()
                                                    }, false)
                                                    return
                                                }
                                                question.data.push(e1)
                                                store.hideFormDialog()
                                                question.waitingForUpload = 2
                                                question.resetQuestionIndexes()
                                                refreshPage()
                                            }, () => store.hideModal2())
                                        }
                                    })
                                }
                                if (question.waitingForUpload === 3) {
                                    return [
                                        controls.button({
                                            title: '已完成导入',
                                            leftIcon: 'ok',
                                            type: 'success',
                                            callBack() {
                                                tool.toast.success('全部成功导入')
                                            }
                                        }),
                                        controls.label({
                                            title: '重开当前页面可以导入其他试卷',
                                            style: {
                                                color: 'red'
                                            }
                                        }),
                                    ]
                                }
                                if (question.waitingForUpload === 1) {
                                    return [
                                        controls.label({
                                            title: '上传答案文件后可以编辑现有题目和添加新题目',
                                            style: {
                                                color: 'red'
                                            }
                                        }),
                                        controls.button({
                                            title: '解析答案文件',
                                            leftIcon: 'upload',
                                            callBack() {
                                                answer.selectFile()
                                            }
                                        })
                                    ]
                                }
                                if (question.waitingForUpload === 0) return [
                                    controls.button({
                                        title: '解析题目文件（仅限选择题）',
                                        leftIcon: 'upload',
                                        callBack() {
                                            question.selectFile()
                                        }
                                    }),
                                    add()
                                ]
                                if (question.waitingForUpload === 2) {
                                    return [
                                        controls.button({
                                            title: '提交',
                                            leftIcon: 'submit',
                                            type: 'primary',
                                            async callBack() {
                                                let repo = {}
                                                for (let i = 0; i < question.data.length; i++) {
                                                    let ck = tool.checkQuestionItem(question.data[i])
                                                    ck.forEach(item => {
                                                        if (repo[item] === undefined) repo[item] = []
                                                        repo[item].push(question.data[i].index)
                                                    })
                                                }
                                                let str = '所有题目都没有问题了才能上传。有问题的题目：\n'
                                                await tool.object.for(repo, (k, v) => {
                                                    str += `${k}：${v.join('、')}\n`
                                                })
                                                if (Object.keys(repo).length !== 0) {
                                                    store.showModal2('无法上传', str, () => {
                                                        store.hideModal2()
                                                    }, false)
                                                    return
                                                }
                                                let type
                                                let questionTypeError = false
                                                for (let i = 0; i < question.data.length; i++) {
                                                    if (type === undefined) {
                                                        type = question.data[i].type
                                                    } else {
                                                        if (type !== question.data[i].type) {
                                                            questionTypeError = true
                                                            break
                                                        }
                                                    }
                                                }
                                                if (questionTypeError) {
                                                    store.showModal2('无法上传', '所有题目的类型需要一致', () => {
                                                        store.hideModal2()
                                                    }, false)
                                                    return
                                                }
                                                let catelst = await tool.requestData('/category/getList', {}, {}, 'get')
                                                if (catelst.status) {
                                                    catelst = (() => {
                                                        let re = []
                                                        for (let i = 0; i < catelst.data.length; i++) {
                                                            re.push({
                                                                value: catelst.data[i].id,
                                                                title: catelst.data[i].name
                                                            })
                                                        }
                                                        return re
                                                    })()
                                                } else {
                                                    store.showModal2('无法上传', '无法获取类别列表。', () => store.hideModal2(), false)
                                                    return
                                                }
                                                store.showFormDialog('填写试卷信息', [], [
                                                    {
                                                        field: 'categoryId',
                                                        title: '类别',
                                                        type: catelst
                                                    },
                                                    {
                                                        field: 'paperName',
                                                        title: '试卷名称'
                                                    }
                                                ], paperInfo, false, async (e) => {
                                                    for (let i = 0; i < question.data.length; i++) {
                                                        question.data[i].stems = question.data[i].stems.replaceAll("'", '"')
                                                        question.data[i].optionA = question.data[i].optionA.replaceAll("'", '"')
                                                        question.data[i].optionB = question.data[i].optionB.replaceAll("'", '"')
                                                        question.data[i].optionC = question.data[i].optionC.replaceAll("'", '"')
                                                        question.data[i].optionD = question.data[i].optionD.replaceAll("'", '"')
                                                        question.data[i].analysis = question.data[i].analysis.replaceAll("'", '"')
                                                        question.data[i].keywords = question.data[i].keywords.replaceAll("'", '"')
                                                        question.data[i].modified = 1
                                                    }
                                                    await tool.flow(async () => {
                                                        let re = await tool.requestData('/paper/import', {}, {
                                                            ...paperInfo,
                                                            ...e,
                                                            list: question.data,
                                                            isEssay: type !== '选择'
                                                        }, 'post')
                                                        if (re.status) {
                                                            question.waitingForUpload = 3
                                                            store.hideFormDialog()
                                                            refreshPage()
                                                        } else {
                                                            throw re.content
                                                        }
                                                    }, err => tool.toast.error(`${err}`))
                                                })
                                            }
                                        }),
                                        add()
                                    ]
                                }
                                return []
                            })(),
                            ...(() => {
                                if (question.waitingForUpload === 1 || question.waitingForUpload === 3) {
                                    return []
                                }
                                return controls.mSelectControls(() => question.mselect.getList(),
                                    e => question.mselect.setList(e),
                                    () => refreshPage(),
                                    [
                                        {
                                            title: '删除已选',
                                            leftIcon: '删除',
                                            op: 'deleteSelected',
                                            callBack(e) {
                                                store.showModal2(`提示`, `是否删除已选的${question.mselect.getList().length}个问题？`
                                                    , async () => {
                                                        let list = question.mselect.getList()
                                                        list.forEach(item => {
                                                            question.data = question.data.filter(ele => ele.index !== item)
                                                        })
                                                        question.resetQuestionIndexes()
                                                        store.hideModal2()
                                                        question.mselect.removeAll()
                                                        if (question.data.length === 0) {
                                                            question.waitingForUpload = 0
                                                        }
                                                        refreshPage()
                                                    }, true, () => store.hideModal2())
                                            }
                                        }
                                    ],
                                    () => tool.selectValueOfObjectByKey(question.data, 'index'),
                                )
                            })()
                        ],
                        data: {
                            type: (() => {
                                if (question.data.length) {
                                    return 'table'
                                } else {
                                    return ''
                                }
                            })(),
                            enableSelect: (() => {
                                if (question.waitingForUpload === 3) return false
                                if (question.waitingForUpload === 1) return false
                                return true
                            })(),
                            form: [
                                {
                                    field: 'index',
                                    title: '题号'
                                },
                                {
                                    field: 'needCheck',
                                    title: '需要检查'
                                },
                                {
                                    field: 'stems',
                                    title: '题干'
                                },
                                {
                                    field: 'img',
                                    title: '题图'
                                },
                                {
                                    field: 'type',
                                    title: '类型'
                                },
                                {
                                    field: 'answer',
                                    title: '答案'
                                },
                                {
                                    field: 'optionA',
                                    title: '选项A'
                                },
                                {
                                    field: 'optionB',
                                    title: '选项B'
                                },
                                {
                                    field: 'optionC',
                                    title: '选项C'
                                },
                                {
                                    field: 'optionD',
                                    title: '选项D'
                                },
                                {
                                    field: 'analysis',
                                    title: '解析'
                                }
                            ],
                            list: (() => {
                                let data = tool.deepCopyObject(question.data)
                                data.forEach(item => {
                                    if (Array.isArray(item.needCheck)) item.needCheck = item.needCheck.join('，')
                                    item._selected = question.mselect.is(item.index)
                                    if (question.waitingForUpload === 2) {
                                        item.op = [
                                            {
                                                title: '删除',
                                                icon: '删除',
                                                op: 'delete'
                                            },
                                            {
                                                title: '编辑',
                                                icon: 'edit',
                                                op: 'edit'
                                            },

                                        ]
                                    }
                                    if (item.type === '选择') {
                                        item.optionA = item.options.A
                                        item.optionB = item.options.B
                                        item.optionC = item.options.C
                                        item.optionD = item.options.D
                                        item.optionAType = item.optionTypes.A
                                        item.optionBType = item.optionTypes.B
                                        item.optionCType = item.optionTypes.C
                                        item.optionDType = item.optionTypes.D
                                        if (Array.isArray(item.answer)) item.answer = item.answer.join('')
                                    }
                                    item.needCheck = tool.checkQuestionItem(item).join('、')
                                })
                                return data
                            })(),
                            callBack: async (e) => {
                                console.log(e)
                                if (e.op === 'select') {
                                    question.mselect.add(e.item.index)
                                }
                                if (e.op === 'unselect') {
                                    question.mselect.remove(e.item.index)
                                }
                                if (e.op === 'selectAll') {
                                    question.mselect.add(tool.selectValueOfObjectByKey(question.data, 'index'))
                                }
                                if (e.op === 'unselectAll') {
                                    question.mselect.removeAll()
                                }
                                if (e.op === 'delete') {
                                    store.showModal2('提示', '是否删除此问题？', () => {
                                        question.data = question.data.filter(item => item.index !== e.item.index)
                                        question.resetQuestionIndexes()
                                        question.mselect.remove(e.item.index)
                                        if (question.data.length === 0) {
                                            question.waitingForUpload = 0
                                        }
                                        refreshPage()
                                        store.hideModal2()
                                    }, true, () => store.hideModal2())
                                }
                                if (e.op === 'edit' || e.op === 'rowClick') {
                                    tool.forms.question.edit(e.item, (e1, fm) => {
                                        if (Object.keys(e1).length === 0) {
                                            e1 = tool.deepCopyObject(e.item)
                                        }
                                        e1.options.A = e1.optionA
                                        e1.options.B = e1.optionB
                                        e1.options.C = e1.optionC
                                        e1.options.D = e1.optionD
                                        console.log(e1, 112)
                                        let check = tool.checkQuestionItem(e1)
                                        if (check.length) {
                                            store.showModal2('无法保存编辑', check.join('、'), () => {
                                                store.hideModal2()
                                            }, false)
                                            return
                                        }
                                        for (let i = 0; i < question.data.length; i++) {
                                            if (question.data[i].index === e1.index) {
                                                question.data[i].stems = e1.stems
                                                question.data[i].img = e1.img
                                                question.data[i].type = e1.type
                                                question.data[i].answer = e1.answer
                                                question.data[i].analysis = e1.analysis
                                                question.data[i].options = {
                                                    'A': e1.optionA,
                                                    'B': e1.optionB,
                                                    'C': e1.optionC,
                                                    'D': e1.optionD,
                                                }
                                                fm.forEach(item => {
                                                    if (item.field === 'optionA') question.data[i].optionTypes.A = item.type
                                                    if (item.field === 'optionB') question.data[i].optionTypes.B = item.type
                                                    if (item.field === 'optionC') question.data[i].optionTypes.C = item.type
                                                    if (item.field === 'optionD') question.data[i].optionTypes.D = item.type
                                                })
                                                break
                                            }
                                        }
                                        store.hideFormDialog()
                                        refreshPage()
                                    })
                                }
                                refreshPage()
                            },
                        }
                    },
                ]
            }
        }
    }

    return refresh
}